package keeto.com.vn.classified.ui;


import java.io.File;
import java.util.Hashtable;
import java.util.Random;
import java.util.Vector;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classfied.model.Category;
import keeto.com.vn.classified.adapter.ProductCategoriesAdapterManager;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.utils.StatusMessageUtil;
import keeto.com.vn.classified.utils.Utils;
import keeto.com.vn.classified.utils.ValidatorString;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PostProductActivity extends Activity implements  OnClickListener, OnItemSelectedListener, OnItemClickListener{

	public static final int REQUEST_CODE_CAPTURE = 1;
	public static final int REQUEST_CODE_SELECT = 2;
	public static final int MAX_THUMBNAIL_WIDTH = 120;
	public static final int MAX_THUMBNAIL_HEIGHT = 150;
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	public static final String KEY_CATEGORY_ID = "category_id";
	public static final String KEY_AREA_ID = "area_id";
	public static final String KEY_AREA = "area";

	public static final String PUBLISH_KEY_CONTACT = "contact";

	public static final String PUBLISH_KEY_PHONE = "phone";

	public static final String PUBLISH_KEY_EMAIL = "email";

	public static final String PUBLISH_KEY_DESCRIPTION = "description";
	public static final String PUBLISH_KEY_STATUS = "State";

	public static final String PUBLISH_KEY_CREATE = "CreateBy";
	public static final String PUBLISH_KEY_PRICE = "price";
	public static final String PUBLISH_KEY_TITLE = "title";

	private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
	private static final int RANDOM_STR_LENGTH = 5;

	private ImageButton btnBack;
	private TextView tvTitle;
	private ImageView btnSearch;
	private Spinner spCategory;
	private Spinner spSubcategory;
	private Spinner spRegion;
	private Spinner spStatus;
	private TextView tvTittleProduct;
	private EditText edtTitleProduct;
	private TextView tvPrice;
	private EditText edtPrice;
	private EditText edtContact;
	private TextView tvPhone;
	private EditText edtPhone;
	private TextView tvPostEmail;
	private EditText edtEmail;
	private TextView tvDes;
	private EditText edtDes;
	private ImageButton btn_capture;
	private ImageButton btn_selectImg;
	private Gallery mGallery;
	private Button btnPost;
	private Area mArea = null;
	private String userName = null;
	private String UserPhone = null;
	private static InUIThreadHandler mReturnCodeHandler = null;


	private Vector<Category> vtCategories = null;
	private ArrayAdapter<String> spCategoryAdapter = null;

	private Category CurrentCategory = null;
	private Vector<Category> vtSubCategories = null;
	private ArrayAdapter<String> spSubCategoryAdapter = null;

	private Vector<Area> vtAreas = null;
	private ArrayAdapter<String> spAreaAdapter = null;

	private ArrayAdapter<String> spStatusAdapter = null;
	private Category mSubCategory;

	private String tittleProduct;
	private int priceProduct =0;
	private String Seller;
	private String Phone;
	private String Email;
	private String DesProduct;
	private String Status;
	private Hashtable<String, String> mDataPublish = new Hashtable<String, String>();
	private Vector<String> mImagePathContainer = new Vector<String>();
	private String StrPathImage;
	private Vector<Bitmap> mImageContainer = new Vector<Bitmap>();
	private ScrollView mScrollView;
	private GalleryAdapter mGalleryAdapter = null;
	private ProgressDialog mProgressDialog = null;
	private ViewHandler mHandler = new ViewHandler();
	private PostListener listener = new PostListener();
	private BuiltinService builtservice = null;
	private BuiltinServiceManager mBuiltinServiceManager = null;
	private TelephonyManager  telephonemng ;
	private RelativeLayout llCaptcha;
	private TextView tvCaptcha;
	private EditText edtCaptcha;
	private Button btnCaptcha;
	private String AnswerCaptcha;

	public static void actionLaunch(Context context) {
		Intent i = new Intent(context, PostProductActivity.class);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ia_publish_xml_template_view);
		mReturnCodeHandler = new InUIThreadHandler();
		mArea = IAManager.getInstance(getApplicationContext()).getMyArea();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		telephonemng = (TelephonyManager) PostProductActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
		if (builtservice != null){
			userName = builtservice.getUserName();
		}else{
			userName = null;
			if (telephonemng != null){
				UserPhone = telephonemng.getLine1Number();
			}
		}

		initComponent();
	}


	private void initComponent(){
		btnBack = (ImageButton)findViewById(R.id.btn_sub_title_back);
		tvTitle = (TextView)findViewById(R.id.tv_sub_title_text);
		btnSearch = (ImageView)findViewById(R.id.btn_sub_title_search_home);
		btnSearch.setVisibility(View.GONE);
		spCategory = (Spinner)findViewById(R.id.sp_category);
		spSubcategory = (Spinner)findViewById(R.id.sp_subcategory);
		spRegion= (Spinner)findViewById(R.id.sp_region);
		spStatus = (Spinner)findViewById(R.id.sp_status);
		tvTittleProduct = (TextView)findViewById(R.id.tv_title_product);
		edtTitleProduct = (EditText)findViewById(R.id.edt_title_product);
		tvPrice = (TextView)findViewById(R.id.tv_price_product);
		edtPrice= (EditText)findViewById(R.id.edt_price);
		edtContact= (EditText)findViewById(R.id.edt_contact);
		tvPhone =  (TextView)findViewById(R.id.tv_phone_poster);;
		edtPhone= (EditText)findViewById(R.id.edt_phone);
		tvPostEmail = (TextView)findViewById(R.id.tvPostEmail);
		edtEmail= (EditText)findViewById(R.id.edt_email);
		tvDes = (TextView)findViewById(R.id.tv_deciption);
		edtDes= (EditText)findViewById(R.id.edt_decription);
		btn_capture = (ImageButton)findViewById(R.id.btn_capture);
		btn_selectImg = (ImageButton)findViewById(R.id.btn_select);
		mGallery = (Gallery)findViewById(R.id.image_gallery);
		btnPost = (Button)findViewById(R.id.btn_post);
		mScrollView = (ScrollView)findViewById(R.id.scrollpost);

		llCaptcha = (RelativeLayout)findViewById(R.id.llCaptcha);
		tvCaptcha = (TextView)findViewById(R.id.tvCaptcha);
		edtCaptcha = (EditText)findViewById(R.id.edtCaptcha);
		btnCaptcha = (Button)findViewById(R.id.btn_renewCaptcha);
		btnCaptcha.setOnClickListener(this);
		if (builtservice != null){
			llCaptcha.setVisibility(View.GONE);
		}else{
			llCaptcha.setVisibility(View.VISIBLE);
			createCaptcha();
		}

		/*
		 * init data
		 */
		tvTitle.setText(this.getResources().getString(R.string.menu_bar_post));

		vtCategories = IAManager.getInstance(this).getPublishCategory(ProductCategoriesAdapterManager.ADAPTER_CATEGORY +"");
		String[] listCategory = Utils.getTextofCategory(this,vtCategories);
		spCategoryAdapter =	new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listCategory);
		spCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spCategory.setAdapter(spCategoryAdapter);
		spCategoryAdapter.notifyDataSetChanged();
		vtSubCategories = new Vector<Category>();
		String[] listSubCategories = Utils.getTextofSubCategory(this,vtSubCategories);
		if (listSubCategories != null){
			spSubCategoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listSubCategories);
			spSubCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spSubcategory.setAdapter(spSubCategoryAdapter);
		}

		vtAreas = IAManager.getInstance(this).getAllArea();
		String[] listArea = Utils.getTextofArea(vtAreas);
		spAreaAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listArea);
		spAreaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spRegion.setAdapter(spAreaAdapter);

		String [] listStatus = this.getResources().getStringArray(R.array.arr_sp_status);
		spStatusAdapter = new  ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listStatus);
		spStatusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spStatus.setAdapter(spStatusAdapter);

		btnBack.setOnClickListener(this);
		spCategory.setOnItemSelectedListener(this);
		spSubcategory.setOnItemSelectedListener(this);
		btn_capture.setOnClickListener(this);
		btn_selectImg.setOnClickListener(this);
		btnPost.setOnClickListener(this);

		tvTittleProduct.setText(Html.fromHtml(this.getResources().getString(R.string.ia_publish_title) + "<font color=\"red\">*</font>:"));
		tvPrice.setText(Html.fromHtml(this.getResources().getString(R.string.ia_publish_price) + "<font color=\"red\">*</font>:"));
		tvPhone.setText(Html.fromHtml(this.getResources().getString(R.string.ia_publish_phone_number) + "<font color=\"red\">*</font>:"));
		tvPostEmail.setText(Html.fromHtml(this.getResources().getString(R.string.ia_publish_email) + "<font color=\"red\">*</font>:"));
		tvDes.setText(Html.fromHtml(this.getResources().getString(R.string.ia_publish_description) + "<font color=\"red\">*</font>:"));
		mGalleryAdapter = new GalleryAdapter(this);
		mGallery.setAdapter(mGalleryAdapter);
		mGalleryAdapter.notifyDataSetChanged();
		mGallery.setOnItemClickListener(this);

		if (builtservice == null){
			edtPhone.setText(UserPhone);
		}else{
			edtPhone.setText(builtservice.getUserPhone());
			edtEmail.setText(builtservice.getUserEmail());
			edtContact.setText(builtservice.getDisplayName());

		}
		if (builtservice != null){
			for(int i=0;i<spAreaAdapter.getCount();i++){
				if (vtAreas.elementAt(i).getRemoteId().equals(builtservice.getAreaID())){
					spRegion.setSelection(i);
					break;
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_sub_title_back:
			askQuit();
			break;
		case R.id.btn_capture:
			ChooseImagePreviewActivity.actionTakePhoto(PostProductActivity.this, REQUEST_CODE_CAPTURE);

			break;
		case R.id.btn_select:
			ChooseImagePreviewActivity.actionChoosePicture(PostProductActivity.this, REQUEST_CODE_SELECT);
			break;
		case R.id.btn_renewCaptcha:
			createCaptcha();
			break;
		case R.id.btn_post:
			try {
				validateAndPublish();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
	}

	private void createCaptcha(){
		AnswerCaptcha = getRandomString();
		tvCaptcha.setText(AnswerCaptcha);
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (parent.getId() == spRegion.getId()){

		}else if(parent.getId() == spCategory.getId()){
			if (spCategory.getAdapter() != null && spCategory.getSelectedItemId() >0){
				spSubcategory.setEnabled(true);
				if (position>0){
					CurrentCategory = vtCategories.get(position-1);
				}else{
					CurrentCategory = vtCategories.get(position);
				}

				if (CurrentCategory != null){
					vtSubCategories.clear();
					vtSubCategories = IAManager.getInstance(getApplicationContext()).getPublishCategory(CurrentCategory.getRemoteId());
					String[] listSubCategories = Utils.getTextofSubCategory(this,vtSubCategories);
					if (listSubCategories != null){
						spSubCategoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listSubCategories);
						spSubCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						spSubcategory.setAdapter(spSubCategoryAdapter);
						spSubCategoryAdapter.notifyDataSetChanged();
						spSubcategory.setSelection(0);
					}
				}
			}else{
				spSubcategory.setEnabled(false);
			}
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub

	}
	private void askQuit() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.session_time_out_dialog_title));
		builder.setMessage(getString(R.string.ia_publish_quit_notice_message));
		builder.setPositiveButton(R.string.text_ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}

		});
		builder.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}

		});
		builder.show();

	}

	private void validateAndPublish() throws JSONException {

		getDataAndTemplate();

		tittleProduct = edtTitleProduct.getText().toString();

		Seller = edtContact.getText().toString();
		Phone = edtPhone.getText().toString();
		Email = edtEmail.getText().toString();
		DesProduct = edtDes.getText().toString();
		Status = (String) spStatus.getSelectedItem();


		if (!edtPrice.getText().toString().equals("")){
			priceProduct = Integer.parseInt(edtPrice.getText().toString());
		}else{
			setErrorMsg(this.getResources().getString(R.string.error_price_post), edtPrice);
			edtPrice.requestFocus();
			return;
		}
		if (TextUtils.isEmpty(tittleProduct)){
			setErrorMsg(this.getResources().getString(R.string.error_tittle_post), edtTitleProduct);
			edtTitleProduct.requestFocus();
			return;
		}else if (tittleProduct.length() <5 || tittleProduct.length() >50){
			setErrorMsg(this.getResources().getString(R.string.error_tittle_post_leight), edtTitleProduct);
			edtTitleProduct.requestFocus();
			return;
		}
		if (priceProduct < 1000 || (priceProduct % 500) != 0){
			setErrorMsg(this.getResources().getString(R.string.error_price_post_edit), edtPrice);
			edtPrice.requestFocus();
			return;
		}else if (priceProduct == 0){
			setErrorMsg(this.getResources().getString(R.string.error_price_post), edtPrice);
			edtPrice.requestFocus();
			return;
		}

		if (TextUtils.isEmpty(Phone)){
			setErrorMsg(this.getResources().getString(R.string.ia_public_error), edtPhone);
			edtPhone.requestFocus();
			return;
		}

		ValidatorString strEmailformat = new ValidatorString(EMAIL_PATTERN);

		if (!strEmailformat.validate(Email)){
			setErrorMsg(getResources().getString(R.string.ia_public_error), edtEmail);
			edtEmail.requestFocus();
			return;
		}

		if (TextUtils.isEmpty(DesProduct)){
			setErrorMsg(this.getResources().getString(R.string.ia_public_error), edtDes);
			edtDes.requestFocus();
			return;
		}


		if (mImagePathContainer == null || mImagePathContainer.size() < 1 || mImagePathContainer.size() > 3) {
			Toast.makeText(this, getResources().getString(R.string.ia_public_check_image), Toast.LENGTH_LONG).show();
			return;
		}
		if (llCaptcha.getVisibility() == View.VISIBLE){	
			if (edtCaptcha.getText().toString().equals("")){
				setErrorMsg(this.getResources().getString(R.string.error_ipnut_captcha), edtCaptcha);
				return;

			}else if (!edtCaptcha.getText().toString().equals(AnswerCaptcha)){
				setErrorMsg(this.getResources().getString(R.string.error_fails_captcha), edtCaptcha);
				return;
			}
		}
		if (mSubCategory == null){
			Toast.makeText(this, getResources().getString(R.string.error_fails_sub_category), Toast.LENGTH_LONG).show();
			return;
		}

		JSONObject content = new JSONObject();
		content.put(KEY_CATEGORY_ID, mSubCategory.getRemoteId());
		content.put(KEY_AREA_ID, mArea.getRemoteId());
		content.put(PUBLISH_KEY_CONTACT, Seller);
		content.put(PUBLISH_KEY_EMAIL, Email);
		content.put(PUBLISH_KEY_PHONE, Phone);
		content.put(PUBLISH_KEY_PRICE, priceProduct);
		content.put(PUBLISH_KEY_TITLE, tittleProduct);
		content.put(PUBLISH_KEY_CREATE, userName);
		content.put(PUBLISH_KEY_DESCRIPTION, DesProduct);
		content.put(PUBLISH_KEY_STATUS, Status);


		if (userName != null){
			ClassifiedCore.getInstance(this).taskPublish(content, mImagePathContainer, listener, userName);
		}else if (UserPhone != null){
			ClassifiedCore.getInstance(this).taskPublish(content, mImagePathContainer, listener, UserPhone);
		}else{
			ClassifiedCore.getInstance(this).taskPublish(content, mImagePathContainer, listener, Phone);
		}

		mHandler.showProgressDialog(getString(R.string.ia_publish_message_publishing));

	}
	protected void getDataAndTemplate() {
		/*
		 * get area
		 */

		int selection2 = spRegion.getSelectedItemPosition();
		mArea = vtAreas.get(selection2);

		/*
		 * get Category
		 */
		int postCategory  =	spCategory.getSelectedItemPosition();
		if (postCategory == 0){
			Toast.makeText(this, getString(R.string.error_category), Toast.LENGTH_SHORT).show();
			return;
		}
		int location = spSubcategory.getSelectedItemPosition();
		if (location == 0){
			Toast.makeText(this, getString(R.string.error_sub_category), Toast.LENGTH_SHORT).show();
			return;
		}else{
			mSubCategory = vtSubCategories.get(location -1);
		}
		if (TextUtils.isEmpty(mSubCategory.getPublishTemplate())) {
			Toast.makeText(this, getString(R.string.error_category), Toast.LENGTH_SHORT).show();
		}

	}
	private void setErrorMsg(String msg, EditText viewId) {
		int ecolor = Color.RED; // whatever color you want
		String estring = msg;
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
		ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
		viewId.setError(ssbuilder);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CODE_CAPTURE:
		case REQUEST_CODE_SELECT:
			if (resultCode == RESULT_OK && data != null) {

				StrPathImage = data.getExtras().getString("filepath");

				try {

					File imagefile = new File(StrPathImage);
					long size = imagefile.length();
					Log.e("Size post", "file size in KB:" + size / 1024);

					for (String p : mImagePathContainer) {
						if (p.equals(StrPathImage)) {
							return;
						}
					}
					Bitmap thumbnail = BitmapFactory.decodeFile(StrPathImage);
					mImageContainer.add(thumbnail);
					mImagePathContainer.add(StrPathImage);
					if (mImagePathContainer.size() > 0) {
						mGallery.setVisibility(View.VISIBLE);
						mGallery.setSelection(mImagePathContainer.size() - 1);
						mScrollView.post(new Runnable() {
							@Override
							public void run() {
								mScrollView.fullScroll(View.FOCUS_DOWN);
							}
						});
					}
					mGalleryAdapter.notifyDataSetChanged();

				} catch (Exception e) {
					Toast.makeText(this, StrPathImage, Toast.LENGTH_SHORT).show();
				}
			}
			break;
		}
	}

	class GalleryAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private Context context;


		public GalleryAdapter(Context context) {
			super();
			this.context = context;
			this.inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mImageContainer.size();
		}

		@Override
		public Object getItem(int position) {
			return mImageContainer.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			convertView = inflater.inflate(R.layout.image_gallery_item, null);
			ImageView iv = (ImageView) convertView.findViewById(R.id.image_view);
			Bitmap bmp = mImageContainer.get(position);
			iv.setImageBitmap(bmp);

			return convertView;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		mImageContainer.remove(position);
		mImagePathContainer.remove(position);
		mGalleryAdapter.notifyDataSetChanged();
		if (mImageContainer.size() == 0) {
			mGallery.setVisibility(View.GONE);

		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		askQuit();
	}
	public void disableEditText(EditText editor, final boolean isDisable) {
		editor.setFilters(new InputFilter[] { new InputFilter() {
			@Override
			public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				if (isDisable) {
					return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
				} else {
					return null;
				}
			}
		} });
	}

	class ViewHandler {

		public void addTextToEditor(final EditText editor, final String text) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					disableEditText(editor, false);
					editor.setText(text);
					disableEditText(editor, true);
				}

			});
		}

		public void dismissProgressDialog() {

			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					mProgressDialog.dismiss();
				}

			});
		}

		public void showError(String statusMessageByStatus) {

		}

		public void showLogonAlertDialog() {

			final BuiltinService bs = BuiltinServiceManager.getInstance(getApplicationContext()).getBuitinService();

			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					AlertDialog.Builder builder = new AlertDialog.Builder(PostProductActivity.this)
					.setTitle(R.string.logon_dialog_alert_title)
					.setMessage(getResources().getString(R.string.msg_session_duplicate_message, getResources().getString(R.string.app_name)))
					.setPositiveButton(R.string.text_login, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							//									IMCore.getInstance(getApplication()).taskLogon(bs.getUserName(), bs.getPassword(), IConstant.ONLINE, mListener);

						}
					}).setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							dialog.cancel();

						}
					});
					builder.create().show();
				}

			});
		}

		public void showMessageToast(final String msg) {

			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					//					Toast.makeText(PublishXMLTemplateActivity.this, msg, Toast.LENGTH_SHORT).show();

					AlertDialog.Builder alert = new AlertDialog.Builder(PostProductActivity.this);       
					alert.setTitle("Đăng tin");
					alert.setMessage("Thành công!");
					alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) { 
							finish();
						}
					});        
					alert.show();
				}

			});
		}

		public void showProgressDialog(final String message) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					mProgressDialog = new ProgressDialog(PostProductActivity.this);
					mProgressDialog.setMessage(message);
					mProgressDialog.show();
				}

			});
		}

		public void ShowSetNetworkDialog() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					AlertDialog.Builder builder = new AlertDialog.Builder(PostProductActivity.this);
					builder.setTitle(R.string.session_time_out_dialog_title);
					builder.setMessage(R.string.msg_connection_timeout);
					builder.setPositiveButton(R.string.session_time_out_dialog_network, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// switch to the Network Setting UI.
							Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
							PostProductActivity.this.startActivity(intent);
						}
					});

					builder.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
					builder.create().show();
				}

			});
		}
	}

	public String getRandomString(){
		StringBuffer randStr = new StringBuffer();
		for (int i = 0; i < RANDOM_STR_LENGTH; i++) {
			int number = getRandomNumber();
			char ch = _CHAR.charAt(number);
			randStr.append(ch);
		}
		return randStr.toString();
	}

	private int getRandomNumber() {
		Random random = new Random();
		int randomInt = 0;
		randomInt = random.nextInt(_CHAR.length());
		if (randomInt - 1 == -1) {
			return randomInt;
		} else {
			return randomInt - 1;
		}
	}


	class PostListener extends ClassifiedListener{
		@Override
		public void finishPostPublish(int returnCode, String string) {
			// TODO Auto-generated method stub
			super.finishPostPublish(returnCode, string);
			if (returnCode == IProtocol.STATUS_CODE_OK_200) {

				String message = StatusMessageUtil.getInstance(PostProductActivity.this).getStatusMessageByStatus(returnCode);
				mHandler.showMessageToast(message);
				mHandler.dismissProgressDialog();

			} else {
				mHandler.dismissProgressDialog();
				mReturnCodeHandler.takeActionByReturnCode(PostProductActivity.this, returnCode, true);
			}
		}
	}
}
